#include "fpga_interface.h"
#include "sense_node.h"

float convert_freq(uint16_t in) {
    float freq;
    if (in < 0x2000) {
        freq = 204.8 - in * 204.8 / 16384;
    } else {
        freq = in * 204.8 / 16384;
    }
    return freq;
}

int main(int argc, char *argv[]) {
    uint32_t cnt = 0;
    uint16_t *fft_ram;

    fpga_init(0);

    if (argc != 2) {
        printf("请输入门限！\n");
        return -1;
    };
    uint32_t level = strtoll(argv[1], NULL, 0);
    printf("门限等于%d\n", level);
    start_FFT_once(level);
    while (get_FFT_state() != 1 && cnt < 10000) {
        cnt++;
    }
    if (cnt >= 10000)
        printf("Timeout!\n");

    fft_ram = read_FFT_RAM();
    for (int i = 0; i < 256; i++) {
        printf("%04x ", fft_ram[i]);
        if ((i + 1) % 16 == 0)
            printf("\n");
    }

    uint64_t len = *(uint64_t *)&fft_ram[0];
    if (len > FFT_RAM_SIZE - 4)
        len = FFT_RAM_SIZE - 4;

    printf("freq      bandwidth   amplitude\n");
    for (int i = 0; i < len; i++) {
        uint16_t freq_raw = fft_ram[i * 4 + 6];
        uint16_t high_freq_raw = fft_ram[i * 4 + 7];
        uint32_t amplitude = *(uint32_t *)&fft_ram[i * 4 + 4];
        float mid_freq, bandwidth;
        mid_freq = convert_freq(freq_raw);
        if (high_freq_raw > 0) {
            bandwidth = (convert_freq(high_freq_raw) - mid_freq) * 2;
        } else {
            bandwidth = 0;
        }
        printf("%-10.2f%-12.2f%d\n", mid_freq, bandwidth, amplitude);
    }

    close_fpga(0);
    return 0;
}
